#!/usr/bin/python
# -*- coding: utf-8 -*-

import ConfigParser
from daemon import DaemonContext
from daemon.pidfile import PIDLockFile
import sys
import os
import time
import signal

import StorageEngine
import CameraControl
from datetime import datetime
import random

import logging

mydir = os.path.dirname( os.path.abspath(__file__) )
sys.path.append( mydir )

from server import *

def get_daemon_config(config_path='../camfw.conf'):
    config = ConfigParser.SafeConfigParser()
    config.read(config_path)

    resp = {}
    config_items = ['workdir', 'pidfile', 'logfile',
                    'bind_address', 'bind_port', 'listen_limit']
    for key in config_items:
        resp[key] = config.get('camfwd', key)

    return resp

if __name__ == '__main__':
    os.chdir( mydir )

    # デーモン起動準備
    config = get_daemon_config()

    if os.path.exists(config['pidfile']):
        print "camfwd is running..."
        exit()

    context = DaemonContext(
            working_directory=config['workdir'],
            pidfile=PIDLockFile(config['pidfile']),
            stderr=open(config['logfile'], 'w+')
    )

    # TODO : signal mapping

    # デーモン処理
    with context:
        # ストレージエンジンとカメラのコントローラを取得
        storage = StorageEngine.Controller()
        ipCam   = CameraControl.Controller()
        # サーバを開始
        server = Server( bind=(config['bind_address'], int(config['bind_port'])),
                listen=int(config['listen_limit']), storage=storage, ipCam=ipCam)
        server.start()

    context.close()

    logging.info('Exit Daemon')

